package org.web.abc.stockanalysis.server.biz.impl;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import lombok.Getter;
import lombok.Setter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.web.abc.stockanalysis.server.domain.StockTaskDO;
import org.web.abc.stockanalysis.server.domain.query.QueryStockTask;
import org.web.abc.stockanalysis.server.helper.HttpHelper;
import org.web.abc.stockanalysis.server.service.StockTaskService;
import org.web.base.helper.StringHelper;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.CountDownLatch;

@Setter
@Getter
public class StockFinanceTask implements Runnable {

    private static final Logger logger = LogManager.getLogger(StockFinanceTask.class);


    private StockTaskDO stockTaskDO;
    private StockTaskService stockTaskService;
    private final CountDownLatch latch;
    private BatchTaskDO batchTaskDO;

    public StockFinanceTask(StockTaskService stockTaskService, CountDownLatch latch, StockTaskDO stockTaskDO, BatchTaskDO batchTaskDO) {
        this.stockTaskService = stockTaskService;
        this.latch = latch;
        this.stockTaskDO = stockTaskDO;
        this.batchTaskDO = batchTaskDO;
    }

    @Override
    public void run() {
        String result = null;
        try {
            QueryStockTask queryStockTask = new QueryStockTask();
            queryStockTask.setExecuteDate(stockTaskDO.getExecuteDate());
            queryStockTask.setStockCode(stockTaskDO.getStockCode());
            queryStockTask.setAnalysisTaskName(TaskDefinitionEnum.STOCK_DAY_PRICE_FULL.getTaskName());
            StockTaskDO stockTaskDOFromDB = stockTaskService.selectOneStockTask(queryStockTask);
            if (stockTaskDOFromDB != null && "completed".equalsIgnoreCase(stockTaskDOFromDB.getAnalysisStatus())) {
                // 任务完成，计数器减 1
                return;
            }

            if (stockTaskDOFromDB != null) {
                stockTaskDO.setStockTaskId(stockTaskDOFromDB.getStockTaskId());
                stockTaskDO.setAnalysisStatus("running");
                // TODO需要清除历史数据，
                stockTaskService.updateStockTaskByStockTaskId(stockTaskDO);
            } else {
                stockTaskDO.setStockCode(stockTaskDO.getStockCode());
                stockTaskDO.setStockName(stockTaskDO.getStockName());
                stockTaskDO.setExecuteDate(stockTaskDO.getExecuteDate());
                stockTaskDO.setAnalysisTaskName(TaskDefinitionEnum.STOCK_DAY_PRICE_FULL.getTaskName());
                stockTaskDO.setAnalysisStatus("running");
                stockTaskService.insertStockTask(stockTaskDO);
            }
            long currentTime = System.currentTimeMillis();
            result = HttpHelper.requestByGet(buildHttp(stockTaskDO, batchTaskDO));
            Gson gson = new Gson();
            // 解析 JSON 为 JsonObject
            JsonObject jsonObject = gson.fromJson(result, JsonObject.class);
            // 获取字段值（支持多种类型转换）
            boolean success = jsonObject.get("success").getAsBoolean();
            Integer taskCost = (int) Math.round((System.currentTimeMillis() - currentTime) / 1000.0);
            stockTaskDO.setTaskCost(taskCost);
            stockTaskDO.setTaskResult(StringHelper.truncateString(result, 1000));
            if (success) {
                stockTaskDO.setAnalysisStatus("completed");
            } else {
                stockTaskDO.setAnalysisStatus("error");
            }
        } catch (Exception e) {
            stockTaskDO.setAnalysisStatus("error");
            e.printStackTrace();
        } finally {
            stockTaskService.updateStockTaskByStockTaskId(stockTaskDO);
            latch.countDown();
        }
    }

    private static String buildHttp(StockTaskDO stockTaskDO, BatchTaskDO batchTaskDO) throws UnsupportedEncodingException {
        String start_date = batchTaskDO.getExtendMap().get("start_date");
        String end_date = batchTaskDO.getExtendMap().get("end_date");
        String encodedName = URLEncoder.encode(stockTaskDO.getStockName(), "UTF-8");

        String url = "http://localhost:8000/api/stocks/sync?stock_code=" +
                stockTaskDO.getStockBasicDO().getExchangeName().toLowerCase() + stockTaskDO.getStockCode() +
                "&stock_name=" + encodedName +
                "&start_date=" + start_date +
                "&end_date=" + end_date;
        logger.info(url);
        return url;
    }
}
